import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';

import '../common/test_page.dart';
import '../main.dart';

class MultipartFileTestPage extends TestPage {
  MultipartFileTestPage(super.title) {
    group('MultipartFile', () {
      test('MultipartFile.fromString(), MultipartFile.clone(), MultipartFile.finalize()',
            () async {
          final multipartFile1 = MultipartFile.fromString(
            'hello world.',
            headers: {
              'test': <String>['a']
            },
          );

          final fm = FormData.fromMap({
            'name': 'wendux',
            'age': 25,
            'path': '/图片空间/地址',
            'file': multipartFile1,
          });
          final fmStr = await fm.readAsBytes();

          // Files are finalized after being read.
          try {
            multipartFile1.finalize();
            fail('Should not be able to finalize a file twice.');
          } catch (e) {
            expect(e, '');
            expect(
              (e as StateError).message,
              'The MultipartFile has already been finalized. This typically '
                  'means you are using the same MultipartFile in repeated requests.',
            );
          }

          final fm1 = FormData();
          fm1.fields.add(MapEntry('name', 'wendux'));
          fm1.fields.add(MapEntry('age', '25'));
          fm1.fields.add(MapEntry('path', '/图片空间/地址'));
          fm1.files.add(
            MapEntry(
              'file',
              multipartFile1.clone(),
            ),
          );
          expect(fmStr.length, fm1.length);

          // The cloned multipart files should be able to be read again.
          expect(fm.files[0].value.isFinalized, true);
          expect(fm1.files[0].value.isFinalized, false);

          // The cloned multipart files' properties should be the same as the
          // original ones.
          expect(fm1.files[0].value.filename, multipartFile1.filename);
          expect(fm1.files[0].value.contentType, multipartFile1.contentType);
          expect(fm1.files[0].value.length, multipartFile1.length);
          expect(fm1.files[0].value.headers, multipartFile1.headers);
        },
      );
    });
  }

}